<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单ID" prop="orderId">
        <el-input v-model="queryParams.oid" placeholder="请输入订单Id" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>


      <!-- <el-form-item label="用户id" prop="uid">
        <el-input v-model="queryParams.uid" placeholder="请输入用户id" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="商家id" prop="storeId">
        <el-input v-model="queryParams.storeId" placeholder="请输入商家id" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="用户电话" prop="userPhone">
        <el-input v-model="queryParams.userPhone" placeholder="请输入用户电话" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="商品ID" prop="pid">
        <el-input v-model="queryParams.pid" placeholder="请输入商品id" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品" prop="pname">
        <el-input v-model="queryParams.pname" placeholder="请输入商品" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="快递单号" prop="deliveryId">
        <el-input v-model="queryParams.deliveryId" placeholder="请输入快递单号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="订单状态" prop="shipmentStatus">
        <el-select v-model="queryParams.shipmentStatus" placeholder="请选择订单状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="createTime">
        <DatePicker v-model="cTime" :timevalue1="cTime"></DatePicker>
      </el-form-item>
      <el-form-item style="display: block">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ds:productOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ds:productOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ds:productOrder:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['ds:productOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productOrderList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" max-width="185" align="center" />
      <el-table-column label="ID" align="center" prop="id" max-width="50" />
      <el-table-column label="父订单ID" align="center" prop="oid" max-width="50" />
      <el-table-column label="商品ID" align="center" prop="pid" max-width="50" />
      <el-table-column label="姓名" align="center" prop="parentArr.realName" max-width="86" />
      <el-table-column label="用户电话" align="center" prop="parentArr.userPhone" max-width="156" />

      <!-- <el-table-column
        label="商家id"
        align="center"
        prop="storeId"
        width="100"
      /> -->
      <!-- <el-table-column
        label="商品名称"
        align="center"
        prop="remark"
        max-width="700"
      /> -->
      <!-- <el-form-item label="图片">
          <ImageUpload v-model="productOrderList.realName"></ImageUpload>
      </el-form-item> -->
      <el-table-column label="商品名称" align="center" prop="pname" max-width="700" />
      <el-table-column label="价格" align="center" prop="totalPrice" max-width="400" />
      <el-table-column label="购买数量" align="center" prop="parentArr.totalNum" max-width="80" />
      <el-table-column label="地址" align="center" prop="parentArr.userAddress" max-width="400" />
      <el-table-column
        label="订单状态"
        align="center"
        prop="parentArr.shipmentStatus"
        width="80"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.shipmentStatus == 0">未发货</span>
          <span v-if="scope.row.shipmentStatus == 1">待收货</span>
          <span v-if="scope.row.shipmentStatus == 2">已收货</span>
        </template>
      </el-table-column>

      <el-table-column label="支付时间" align="center" prop="parentArr.createTime" max-width="156" />


      <!-- <el-table-column label="商品规格" align="center" prop="name" max-width="156" /> -->



    </el-table>


    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :visible.sync="dialogShow" width="740" append-to-body>
      <el-table :data="orderGoodsList">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="realName" label="姓名"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="totalPrice" label="总价"></el-table-column>
        <el-table-column prop="totalNum" label="数量"></el-table-column>
        <el-table-column prop="userAddress" label="地址"></el-table-column>
      </el-table>
    </el-dialog>


    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="uid">
          <el-input disabled="disabled" v-model="form.uid" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input disabled="disabled" v-model="form.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户电话" prop="userPhone">
          <el-input disabled="disabled" v-model="form.userPhone" placeholder="请输入用户电话" />
        </el-form-item>
        <el-form-item label="详细地址" prop="userAddress">
          <el-input disabled="disabled" v-model="form.userAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="商品id" prop="pid">
          <el-input disabled="disabled" v-model="form.pid" placeholder="请输入商品id" />
        </el-form-item>
        <el-form-item label="商品" prop="productName">
          <el-input disabled="disabled" v-model="form.productName" placeholder="请输入商品" />
        </el-form-item>
        <el-form-item label="购买数量" prop="totalNum">
          <el-input disabled="disabled" v-model="form.totalNum" placeholder="请输入购买数量" />
        </el-form-item>
        <el-form-item label="订单编号" prop="totalPrice">
          <el-input disabled="disabled" v-model="form.totalPrice" placeholder="请输入订单总价" />
        </el-form-item>
        <el-form-item label="订单号" prop="totalPrice">
          <el-input disabled="disabled" v-model="form.orderId" placeholder="订单号" />
        </el-form-item>
        <el-form-item label="快递单号" prop="deliveryId">
          <el-input v-model="form.deliveryId" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="快递公司" prop="deliveryNumber">
          <el-select v-model="form.deliveryNumber" placeholder="请选择快递公司" clearable>
            <el-option v-for="item in companyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="shipmentStatus">
          <el-radio-group v-model="form.shipmentStatus">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="parseInt(dict.dictValue)">{{
            dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProductOrder,
  getProductOrder,
  delProductOrder,
  addProductOrder,
  updateProductOrder,
  exportProductOrder,
} from "@/api/ds/productOrder";
import ImageUpload from "@/components/ImageUpload";

import { storeOrderList, scheduleWebOrderList } from "@/api/ds/storeOrderList";
import { listMealOrder } from "@/api/ds/mealOrder";

import { addAchievement, chargeback, childOrder, childOrderSub } from "@/api/ds/orderManage";
import delivery from "@/utils/delivery";
import DatePicker from "@/components/DatePicker";
import index from "watch-size";

export default {
  name: "ProductOrder",
  components: { DatePicker, ImageUpload },
  data() {
    var validateID = (rule, value, callback) => {
      if (value) {
        if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
          callback(new Error("请输入正确的值"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入值"));
      }
    };

    return {
      // 遮罩层
      loading: true,
      pickerOptions: {
        // 设置不能选择的日期
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate0 = minDate.getTime();
          if (maxDate) {
            this.choiceDate0 = "";
          }
        },
        disabledDate: (time) => {
          let choiceDateTime = new Date(this.choiceDate0).getTime();
          const minTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() - 1
          );
          const maxTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() + 1
          );
          const min = minTime;
          const newDate =
            new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1;
          const max = newDate < maxTime ? newDate : maxTime;
          //如果已经选中一个日期 则 返回 该日期前后一个月时间可选
          if (this.choiceDate0) {
            return time.getTime() < min || time.getTime() > max;
          }
          //若一个日期也没选中 则 返回 当前日期以前日期可选
          return time.getTime() > newDate;
        },
      },
      // 选中数组
      ids: [],
      totalPrice: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      productOrderList: [],
      payTime: [],
      cTime: [], //搜索框 时间选择器数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 加单弹出层
      addOrderDialog: false,
      // 减单弹出层
      minusOrderDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        uid: null,
        pid: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        productName: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        payTime: null,
        payType: null,
        status: null,
        shipmentStatus: null, //快递状态
        refundStatus: null,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        isDel: null,
        cost: null,
        storeId: null,
        shippingType: null,
        channel: null,
        isSystemDel: null,
        regionalPerformance: null,
        communityPerformance: null,
        netBodyNumber: null,
      },
      // 订单状态字典
      statusOptions: [
        // 0未发货 1已发货 2已收货
        { dictValue: 0, dictLabel: "未发货" },
        { dictValue: 1, dictLabel: "待收货" },
        { dictValue: 2, dictLabel: "已收货" },
      ],
      // 表单参数
      form: {},
      deliveryForm: {
        delivery_id: "", //快递单号
        delivery_company: "", //快递公司
        status: "", //快递状态
        userPhone: "", //手机
      },
      companyOptions: [], // 快递公司简称合集
      // 表单校验
      rules: {
        uid: [{ required: true, message: "用户id不能为空", trigger: "blur" }],
        userId: [{ required: true, validator: validateID, trigger: "blur" }],
        productId: [{ required: true, validator: validateID, trigger: "blur" }],
        totalNum: [{ required: true, validator: validateID, trigger: "blur" }],
        deliveryId: [
          { required: true, message: "快递单号不能为空", trigger: "blur" },
        ],
        deliveryNumber: [
          { required: true, message: "快递公司不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },

      //
      orderGoodsList: [],
      dialogShow: false,
    };
  },
  created() {
    this.companyOptions = delivery;
    this.getList();
  },
  methods: {
    async handleSend(row) { },
    async checkGoods(row) {
      let res = await scheduleWebOrderList({ oid: row.id });
      if (res.code === 200) {
        this.orderGoodsList = res.rows;
        this.dialogShow = true;
      }
    },
    /** 查询订单列表 */
    async getList() {
      this.loading = true;

      let queryParams = this.addDateRange(this.queryParams, this.cTime, "")
      let response = await childOrder(queryParams)
      if (response.code === 200) {
        this.productOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      }

      let arr = this.productOrderList.map((item, index) => {
        return new Promise(async (resolve, reject) => {
          let res = await storeOrderList({ id: item.oid })
          if (res.code === 200) {
            resolve(res)

          } else {
            reject("错误")
          }

        })
      })

      let resList = await Promise.all(arr)
      resList.forEach((item, index) => {
        this.$set(this.productOrderList[index], 'parentArr', item.rows[0])
      })
      // this.productOrderList=this.productOrderList.reverse()
    },


    // listProductOrder(
    //   this.addDateRange(this.queryParams, this.cTime, "")
    // ).then((response) => {
    //   this.productOrderList = response.rows;
    //   this.total = response.total;
    //   this.loading = false;
    // });

    // childOrder(this.addDateRange(this.queryParams, this.cTime, "")).then(
    //   (response) => {
    //     this.productOrderList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   }
    // );
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.cTime = [];
      this.form = {
        id: null,
        orderId: null,
        uid: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        pid: null,
        productName: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        payTime: null,
        payType: null,
        status: 0,
        refundStatus: 0,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        isDel: null,
        cost: null,
        shippingType: null,
        channel: null,
        isSystemDel: null,
        remark: null,
        createTime: null,
        regionalPerformance: null,
        communityPerformance: null,
        netBodyNumber: null,
      };
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.totalPrice = selection.map((item) => item.totalPrice);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      getProductOrder(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateProductOrder(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductOrder(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除订单编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delProductOrder(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      let queryParams = this.addDateRange(this.queryParams, this.cTime, "")
      // const queryParams = this.queryParams;

      this.$confirm("是否确认导出所有订单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return childOrderSub(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },


};
</script>


